﻿using System;
using System.Linq;
using System.Text;
using FileClient.Core.Client;
using FileCommon.Extensions;
using FileCommon.Models;
using FileEfCore.DbContexts;
using FileEfCore.FileInfo;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace FileClient.Wpf.Ws;

public class FileService : WebSocketBehavior
{
    protected override async void OnMessage(MessageEventArgs e)
    {
        try
        {
            var data = e.Data;
            var fileMessageInput = ReceivedWsMessage(data);
            var fileClient = App.ServiceProvider.GetRequiredService<IFileServiceClient>();
            await fileClient.FileOperation(fileMessageInput.LocalFileName, fileMessageInput.ServerFileName,fileMessageInput.FileId,
                fileMessageInput.OperationType);
            fileClient.OnTransferHandle += (sender, args) =>
            {
                var outputLine = JsonConvert.SerializeObject(args);
                if (Context.WebSocket.IsAlive)
                {
                    Context.WebSocket.Send(outputLine);
                }
            };
            fileClient.OnTransferCompleteHandle += (sender, args) =>
            {
                var outputLine = JsonConvert.SerializeObject(args);
                if (Context.WebSocket.IsAlive)
                {
                    Context.WebSocket.Send(outputLine);
                }
            };
            fileClient.OnTransferExceptionHandle += (sender, args) =>
            {
                var outputLine = JsonConvert.SerializeObject(new TransferEventArgs()
                {
                    FileName = args.FileName,
                    ServerFileName = args.ServerFileName,
                    ErrorMessage = args.Exception.Message,
                    ProgressStatus = ProgressStatus.Error,
                    MD5Hash = args.MD5Hash
                });
                if (Context.WebSocket.IsAlive)
                {
                    Context.WebSocket.Send(outputLine);
                }
            };
        }
        catch (Exception ex)
        {
            var wsFileOutput = new FileMessageOutput()
            {
                ProgressStatus = ProgressStatus.Error,
                ErrorMessage = ex.Message
            };
            var outputLine = JsonConvert.SerializeObject(wsFileOutput);
            Context.WebSocket.Send(outputLine);
        }
    }

    private FileMessageInput ReceivedWsMessage(string receiveLine)
    {
        if (!receiveLine.IsValidJson())
        {
            throw new Exception("您输入的消息格式不正确");
        }

        var input = JsonConvert.DeserializeObject<FileMessageInput>(receiveLine);
        if (string.IsNullOrWhiteSpace(input.LocalFileName))
        {
            throw new Exception("指定的本地文件完全路径名不允许为空");
        }

        if (string.IsNullOrWhiteSpace(input.ServerFileName) && string.IsNullOrWhiteSpace(input.FileId))
        {
            throw new Exception("请指定需要下载的文件");
        }

        return input;
    }

    protected override void OnClose(CloseEventArgs e)
    {
        base.OnClose(e);
    }
}